# -*- coding: utf-8 -*-

__author__ = 'wangleijie'
print __author__

#使用输出
# x=input(" ");
# print x;

#字符串方法;
a="wang lei jie ";
print a.find("lei");

# join方法测试；
li = ["1","2","3"]
print "".join(li);

# lower方法：
print "hello".upper();
if "Gamble" in ["Gamble","Smith","Noodles"]:
    print "there is it"
# list tuple dict str
print list("wangleijie")
print tuple("wangleijie")
print dict(name="hello",grub="world");

l=[1,2,4]
a={"ceil":"123","cil":"321"};
print a["ceil"]
print "the phone number of ceil is %(ceil)s, %(cil)s" %a;

# clear函数;
x={"key":"value"};
y=x;
x["key"]="123"
import copy;
z=copy.copy(x)
x["key"]="";
print z;

#copy and deepcopy
print "========"
a={"wang":[1,2,3]};
b=copy.copy(a);
c=copy.deepcopy(a);
a["wang"].remove(1);
print b
print c
print a.get("leijie","no available")

# keys has_key items;;
print a.items();
print a.keys()

# assert
print "===="
age = 100;
# assert  10<age<90

print "hello,world"


# loop while
print "=========="
x=0;
sum1 =0;
while x<=100:
    sum1 = sum1 + x;
    x = x + 1;
print sum1

# prnit map
print "============"
map1 = {"key":"value","key1":"value1"};
for key, value in map1.items():
    print key, "correspond", value

# function
def print_param(*param):
    print param

print_param("hello","world");

def print_param_ex(**param):
    print param
print print_param_ex(name="wang",middle="lei",last="jie");

def add(x,y):
    print x+y;
li = (1,2);
add(*li);

# class definition
print "================"
__metaclass__=type
class MyClass:
    gl = 10;
    def set(self, name="wang"):
        self.name = name;
    def get(self):
        return self.name;

myclass = MyClass();
myclass.set("wang lei jie");
print myclass.get();

print MyClass.__base__;  #print base;
print isinstance(myclass,MyClass)
print isinstance(myclass,object)
print issubclass(MyClass,object)

# exception
print "======exception======="
try:
    1+1;
    # raise Exception("wang")
except Exception, e:
    print e;
else:
    print "else"
finally:
    print "finally"

# 测试porperty函数;
print "======perperty========="
__metaclass__ = type
class PropertyTest:
    def __init__(self):
        self.width = 0;
        self.heigth = 0;
    def fget(self):
        print "fget"
        return self.width, self.heigth;
    def fset(self,size):
        print "fset"
        self.width,self.heigth = size;
    size = property(fget,fset);

MyPorpertyTest = PropertyTest();
MyPorpertyTest.size = (1,2);
print MyPorpertyTest.heigth
print MyPorpertyTest.width;


# new property

__metaclass__ = type
class NewProperty:
    @property
    def score(self):
        return self.__score;
    @score.setter
    def score(self,value):
        if value<10:
            raise ValueError("too small");
        else:
            self.__score=value;

print "=====new property========"
newproperty = NewProperty()
newproperty.score = 12;
print newproperty.score


# static method and class method

print "=====static_class======="
class Static_Class_Method:
    @staticmethod
    def static_method():
        print "I am static method";
    @classmethod
    def class_method(cls):
        print "I am class Method", cls

Static_Class_Method.static_method();
Static_Class_Method.class_method();

# getattr & setattr
print "=====get/set attr======="
class GetSetAttr:
    def __init__(self):
        self.heigth = 0;
        self.width = 0;
    def __getattr__(self, item):
        if item == "size":
            return self.heigth, self.width;
        else:
            raise AttributeError("there is no atrribute");
    def __setattr__(self, key, value):
        if key == "size":
            self.width, self.heigth = value
        elif key == "heigth":
            print "heigth"
        elif key == "width":
            print "width"
        else:
            print "no size";

get_set_attr = GetSetAttr();
# get_set_attr.heigth = 10;
# get_set_attr.width = 11;

# iterator
print "====iteraotr====="
class Fibs:
    def __init__(self):
        self.a = 0;
        self.b = 1;
    def next(self):
        self.a, self.b = self.b, self.a+self.b
        return self.a
    def __iter__(self):
        return self

fibs = Fibs();
for f in fibs:
    if f > 100000:
        print f
        break;

# 生成器：
print "=====generator======="
def flatter(nested):
    for sublist in nested:
        for elment in sublist:
            yield elment;

nested=[[1,2],[2,3],[5]];
for num in flatter(nested):
    print num


print "=======genreator 1 ====="
def repeater(value):
    while True:
        new = yield value;
        if new is not None:
            value = new;

r = repeater(12);
print r
print r.next();
print r.next()
r.send("hello")
print r.next()
#
# from Modules1 import MyPrint
# MyPrint("hello")
# import copy

print "======2015/09/18======"
print "======os======"
import os;
for key in os.environ.keys():
    if key == "PATH":
        print os.environ[key];

# print "=========fileinput========"
# import  fileinput
# for line in fileinput.input(files="Modules1.py",inplace=True ):
#     print "%d : %s" %(fileinput.filelineno(), line)
# fileinput.close();

print "=========fileinput========"
import  time
print time.asctime();
print time.time();
print time.asctime(time.localtime(time.time()))

print "==============random==============="
# import  random;
# print random.random();
# print random.random();
# print random.random();
# print random.randrange(1,100);
# print random.choice([1,2,3])

print "===========shelve==============="
# import shelve
# s = shelve.open("test.py");
# s["x"]=["a","b","c"]
# s["x"].append("d")
# print s["x"]

print "========regular============="
import  re
robject = re.compile('^h(t){1,4}p://python\.org');
if re.search(robject, "http://python.org"):
    print "found it"

print re.escape("www.python.org");

print "=========template============"
# import fileinput
# file_pat = re.compile('\[(.+?)\]')
# scope = {};
# def replacement(match):
#     code = match.group(1);
#     try:
#         return str(eval(code, scope))
#     except SyntaxError:
#         exec code in scope
#         return  "";
# lines = [];
#
# for line in fileinput.input():
#     lines.append(line);
# text = "".join(line);
# print file_pat.sub(replacement, text);

print "============file============="
# file = open("Modules1.py","r");
# print file.readlines()
# file.close();

# file = open("Modules1.py","r");
# for line in file:
#     print line

print "=========";
(a,b) = (1,2);
print a
print b

import module
